<?php
namespace app\index\controller;
use app\classes\helper\AdvertBehavior;
use think\Controller;
use think\Db;
use think\facade\Request;
class Order extends Controller
{
    protected $middleware = ['VerifyLogin'];

    public function create()
    {
        $params = Request::param('', '', 'strip_tags,trim');
        if(isset($params['activity_id']) && $params['activity_id'] >= 1)
        {
            $verify_result = $this->validate($params, 'Order.create_ac');
        }else{
            $verify_result = $this->validate($params, 'Order.create');
        }

        if(true !== $verify_result){
            return json(['code'=>101,'msg'=>$verify_result]);
        }

        $nid = input('nid', 0);
        $activityId = 0;
        if(isset($params['activity_id']) && $params['activity_id'] >= 1)
        {
            $activity = Db::table('pay_recharge_activity')
                ->where('id',$params['activity_id'])
                ->where('delete_time','<',1)
                ->field('pay_times')->findOrEmpty();

            if(empty($activity))
            {
                return json(['code'=>101,'msg'=>'活动不存在']);
            }
            if($activity['pay_times'] == 1)
            {
                $count = Db::table("pay_order_success")->where(['uid' => request()->userInfo['id'], 'recharge_activity_id' => $params['activity_id']])->count();
                if ($count >= 1) {
                    return json(['code'=>101,'msg'=>'您已充值过该活动，下单失败']);
                }
            }
            $activityId = $params['activity_id'];
        }

        $payType = $params['pay_type'];

        $PayLogic = new \app\index\logic\Order();
        $paymentNumber = $PayLogic->getPaymentNumber(request()->quickAppId,$payType);
        if (!$paymentNumber) {
            return json(['code'=>101,'msg'=>'未设置支付号']);
        }

        $changeWhere[] = ['uid', '=', request()->userInfo['id']];
        $changeWhere[] = ['channel_id', '=', request()->userInfo['channel_id']];

        $change_date = Db::table('quick_user_change_log')->where($changeWhere)->force('uid')->order("change_date desc")->value('change_date');

        $date = date("Y-m-d");
        $advertMediaId = 0;
        if(request()->userInfo['channel_id'] > 0)
        {
            $advertMedia = Db::table('quick_user_behavior_monitoring')
                            ->where('channel_id',request()->userInfo['channel_id'])
                            ->where('uid',request()->userInfo['id'])
                            ->order('id DESC')->field('type')->findOrEmpty();

            $advertMediaId = $advertMedia ? $advertMedia['type'] : 0;
        }

        if($activityId > 0)
        {
            $item_id = Db::table('pay_recharge_activity')->where('id',$activityId)->value('item_id');
            $item = Db::table('pay_recharge_item')->where('id',$item_id)->findOrEmpty();
        }else{
            $item = Db::table('pay_recharge_item')->where('id',$params['id'])->findOrEmpty();
        }


        $orderData = [
            'uid'               => request()->userInfo['id'],
            'channel_id'        => request()->userInfo['channel_id'],
            'quick_id'          => request()->userInfo['quick_id'],
            'agent_id'          => request()->userInfo['agent_id'],
            'ip_addr'           => request()->ip(),
            'recharge_type'     => $activityId > 0 ? 2 : 1,
            'recharge_activity_id' => $activityId,
            'user_reg_date'     => request()->userInfo['regdate'],
            'out_trade_no'      => $PayLogic->generateOrderNumber(),
            'trade_no'          => '',
            'total_fee'         => $item['total_fee'],
            'order_desc'        => $item['desc'],
            'status'            => 1,
            'chargefrom'        => $paymentNumber['id'],
            'pay_time'          => 0,
            'type'              => $item['vipdays'] > 0 ? 2 : 1,
            'virtual_currency'  => $item['virtual_currency'],
            'point_gift'        => $item['point_gift'],
            'vipdays'           => $item['vipdays'],
            'pay_type'          => $payType,
            'recharge_times'    => request()->userInfo['pay_times'],
            'nid'               => $nid,
            'phone_model'       => request()->userInfo['provider'],
            'advert_media_id'   => $advertMediaId,
            'is_report'         => 1,
            'user_source_date'  => $change_date ? $change_date : request()->userInfo['regdate'],
            'create_date'       => $date
        ];

        //正常订单
        $oid = Db::table('pay_order')->insertGetId($orderData);

        if ($oid) {
            //记录订单广告相关数据
            $AdvertBehavior = new AdvertBehavior();
            $AdvertBehavior->writeOrderRecord($orderData,$oid);
            try {
                return $PayLogic->callPayment($orderData, $paymentNumber);
            }catch (\Exception $e){

                return json(['code'=>102,'msg'=>$e->getMessage()]);
            }
        } else {
            return json(['code'=>101,'msg'=>'创建订单异常失败']);
        }


    }

}